import React from "react";
import Box from "./Box";
import Text from "./Text";
import Button from "./Button";
import Modal from "./Modal";
import { addMagicPoints } from "./UserMagic";

const CheckInModal = ({ isOpen, onClose }) => {
  if (!isOpen) return null;
  
  const handleCheckIn = () => {
    // 获取今天的日期作为字符串
    const today = new Date().toLocaleDateString();
    
    // 记录本次签到
    localStorage.setItem('last_check_in_date', today);
    
    // 更新签到记录
    updateCheckInRecord();
    
    // 增加50点魔力值
    addMagicPoints(50, "每日签到");
    
    // 检查月度全勤并奖励
    checkMonthlyBonus();
    
    // 关闭弹窗
    onClose();
  };
  
  // 更新签到记录
  const updateCheckInRecord = () => {
    // 获取当前日期
    const today = new Date();
    const year = today.getFullYear();
    const month = today.getMonth() + 1; // 月份从0开始
    const day = today.getDate();
    
    // 当月签到记录的key
    const recordKey = `check_in_record_${year}_${month}`;
    
    // 获取当月签到记录
    let monthRecord = localStorage.getItem(recordKey);
    if (!monthRecord) {
      monthRecord = [];
    } else {
      monthRecord = JSON.parse(monthRecord);
    }
    
    // 如果今天还没签到，则添加签到记录
    if (!monthRecord.includes(day)) {
      monthRecord.push(day);
      localStorage.setItem(recordKey, JSON.stringify(monthRecord));
    }
  };
  
  // 检查月度全勤并奖励
  const checkMonthlyBonus = () => {
    const today = new Date();
    
    // 如果不是月末，不检查
    if (today.getDate() !== getLastDayOfMonth(today)) {
      return;
    }
    
    const year = today.getFullYear();
    const month = today.getMonth() + 1;
    const recordKey = `check_in_record_${year}_${month}`;
    
    // 获取当月签到记录
    const monthRecord = JSON.parse(localStorage.getItem(recordKey) || '[]');
    
    // 获取当月总天数
    const daysInMonth = getLastDayOfMonth(today);
    
    // 判断是否每天都签到了
    if (monthRecord.length >= daysInMonth) {
      // 增加500点月度全勤奖励
      addMagicPoints(500, `${year}年${month}月全勤奖励`);
      
      // 标记已领取全勤奖励
      localStorage.setItem(`monthly_bonus_${year}_${month}`, 'claimed');
    }
  };
  
  // 获取当月的最后一天
  const getLastDayOfMonth = (date) => {
    // 下个月的第0天就是当月的最后一天
    return new Date(date.getFullYear(), date.getMonth() + 1, 0).getDate();
  };
  
  return (
    <Modal close={onClose} isOpen={true}>
      <Box textAlign="center" p={3}>
        <Text as="h3" fontSize={3} mb={4}>
          每日签到
        </Text>
        <Text mb={4}>
          签到可获得<Text as="span" color="primary" fontWeight="bold">50</Text>点魔力值奖励
        </Text>
        <Text mb={4} fontSize={1} color="grey">
          每月完整签到可额外获得<Text as="span" color="primary" fontWeight="bold">500</Text>点魔力值奖励
        </Text>
        <Button onClick={handleCheckIn} width="100%">
          立即签到
        </Button>
      </Box>
    </Modal>
  );
};

export default CheckInModal; 